package Demo2;

class Money implements Cloneable{   //克隆，深拷贝
    public double money = 198.8;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Person implements Cloneable{
    public int age;
    Money m = new Money();  //money是引用，存的地址，克隆也克隆的地址，所以克隆的和原来的是一份

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person tmp = (Person) super.clone();    //克隆Person
        tmp.m = (Money) this.m.clone();         //克隆money
        return tmp;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                '}';
    }
}
public class Test {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person();
        Person person2 = (Person) person1.clone();   //克隆的person类
        System.out.println(person1.m.money);
        System.out.println(person2.m.money);
        System.out.println("======================");
        person1.m.money = 202.2;
        System.out.println(person1.m.money);
        System.out.println(person2.m.money);
    }
    public static void main3(String[] args) throws CloneNotSupportedException {
        Person person = new Person();
        Person person1 = (Person) person.clone();   //克隆的person类
        System.out.println(person.toString());
        System.out.println(person1);
        //System.out.println();这个方法默认就会调用一个继承自Object类型对象的toString方法
        //当System.out.println打印一个对象的时候，会调用对象的toString()方法。(每个对象都会有toString方法)
        System.out.println(person.m.money);
     }
}
